﻿using System;
using System.Text.RegularExpressions;

namespace QA.TFS.Utils
{
    public class RegExHelper
    {
        public delegate void MatchDelegate(MatchCollection collection, EventArgs args);
        public delegate void MatchErrorDelegate(EventArgs args);

        public event MatchDelegate OnMatchFound;
        public event MatchErrorDelegate OnMatchNotFound;

        private String _Regex = "";
        public String Regex
        {
            get
            {
                return _Regex;
            }
            set
            {
                _Regex = value;
            }
        }

        private Boolean _UseSingleline = true;
        public Boolean UseSingleline
        {
            get
            {
                return _UseSingleline;
            }
            set
            {
                _UseSingleline = value;
            }
        }

        private Boolean _UseIgnoreCase = true;
        public Boolean UseIgnoreCase
        {
            get
            {
                return _UseIgnoreCase;
            }
            set
            {
                _UseIgnoreCase = value;
            }
        }

        public void ExtractValue(String content, EventArgs args)
        {
            MatchCollection matches = ExtractValue(content);
            if (matches.Count > 0)
            {
                if (OnMatchFound != null)
                    OnMatchFound(matches, args);
            }
            else
            {
                if (OnMatchNotFound != null)
                    OnMatchNotFound(args);
            }
        }

        public MatchCollection ExtractValue(string content)
        {
            Regex extractor;
            if (_UseSingleline && _UseIgnoreCase)
            {
                extractor = new Regex(_Regex, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            }
            else if (_UseIgnoreCase)
            {
                extractor = new Regex(_Regex, RegexOptions.Singleline);
            }
            else if (_UseSingleline)
            {
                extractor = new Regex(_Regex, RegexOptions.IgnoreCase);
            }
            else
            {
                extractor = new Regex(_Regex);
            }

            return extractor.Matches(content);
        }

        public bool Exists(string content, string expression)
        {
            Regex extractor;
            try
            {
                extractor = new Regex(expression);
                return extractor.IsMatch(content);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
